<template>
  <div>
    <el-dialog
      v-toggle-full="tableHeight"
      v-loading.lock="loading"
      class="base-dialog"
      :custom-class="'panna-dialog_big'"
      title="检测结果录入"
      align="center"
      :visible.sync="innerDialogFormVisible"
      :append-to-body="true"
      @closed="closeDialog"
    >
      <el-form ref="formData" :model="formData" status-icon :rules="formRules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务单号" :label-width="formLabelWidth">{{
              data.entrustTaskNum
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划检测时间" :label-width="formLabelWidth">{{
              formData.planDetectionDate
            }}</el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="检测人" :label-width="formLabelWidth">
              <el-select
                v-model="formData.resultDetectionPersonId"
                placeholder="请选择"
                filterable
                :disabled="updateState"
                style="width: 195px"
              >
                <el-option
                  v-for="item in userData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12"> </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="委托单号" :label-width="formLabelWidth">
              <el-select
                v-model="query.entrustNum"
                placeholder="请选择"
                filterable
                :disabled="updateState"
                style="width: 195px"
                @change="entrustNumChange"
              >
                <el-option
                  v-for="item in entrustNumList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="样品编号" :label-width="formLabelWidth">
              <el-select
                v-model="query.sampleNum"
                placeholder="请选择"
                filterable
                :disabled="updateState"
                style="width: 195px"
                @change="sampleNumChange"
              >
                <el-option
                  v-for="item in sampleNumList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-button
              type="primary"
              :disabled="updateState"
              @click="batchSetResult"
              >批量录入结果</el-button
            >
            <el-button
              type="primary"
              :disabled="updateState"
              @click="batchSetDate"
              >批量设置检测日期</el-button
            >
          </el-col>
          <!-- <el-col v-if="!updateState" :span="12">
            <el-form-item label="批量设置状态" :label-width="formLabelWidth">
              <el-col :span="10">
                <el-checkbox v-model="detectionStateBool">不检测</el-checkbox>
              </el-col>
              <el-col :span="5">
                <el-button type="primary" @click="detectionStateBoolConfirm"
                  >确定</el-button
                >
              </el-col>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>

      <el-table
        ref="table"
        :data="entrustTaskSampleInfoResultDtos"
        :span-method="objectSpanMethod"
        element-loading-text="Loading"
        fit
        height="300px"
        :cell-style="{ background: '#ffffff' }"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-if="!updateState"
          :selectable="setDisabled"
          type="selection"
          width="55"
        ></el-table-column>
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">{{ scope.row.serialNo }}</template>
        </el-table-column>
        <el-table-column label="委托单号" width="190">
          <template slot-scope="scope">{{
            scope.row.entrustOrderNum
          }}</template>
        </el-table-column>
        <el-table-column label="样品编号" width="165">
          <template slot-scope="scope">{{ scope.row.sampleNum }}</template>
        </el-table-column>
        <el-table-column v-if="systemType == 'cdc'" label="受检单位/地址">
          <template slot-scope="scope">{{ scope.row.address }}</template>
        </el-table-column>
        <!-- <el-table-column label="样品类别名称">
          <template slot-scope="scope">{{
            scope.row.sampleCategoryName
          }}</template>
        </el-table-column> -->
        <el-table-column label="样品名称" width="100">
          <template slot-scope="scope">{{ scope.row.sampleName }}</template>
        </el-table-column>
        <el-table-column label="检测项目">
          <template slot-scope="scope">{{ scope.row.detectionItem }}</template>
        </el-table-column>
        <el-table-column label="项目分项">
          <template slot-scope="scope">{{ scope.row.minuteItem }}</template>
        </el-table-column>
        <el-table-column label="单位符号">
          <template slot-scope="scope">{{ scope.row.unitSymbol }}</template>
        </el-table-column>
        <el-table-column label="检测结果" width="130px">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.result"
              filterable
              :disabled="
                updateState ||
                scope.row.dataSubmitState == 20 ||
                scope.row.dataOrigin == 1
              "
              allow-create
              default-first-option
              clearable
              placeholder="检测结果"
              @change="qualified(scope.$index)"
            >
              <el-option
                v-for="item in scope.row.sysBusinessDetectionLimits"
                :key="item.id"
                :label="item.detectionLimit"
                :value="item.detectionLimit"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>

        <!-- <el-table-column label="质控指标">
          <template slot-scope="scope">
            <span>{{
              indicator(scope.row.decisionSymbol, scope.row.number)
            }}</span>
          </template>
        </el-table-column> -->

        <el-table-column label="判定符号">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.decisionSymbol"
              :disabled="updateState || scope.row.dataSubmitState == 20"
              placeholder="请选择"
              @change="qualified(scope.$index)"
            >
              <el-option
                v-for="item in decisionSymbolList"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="判定数值" width="130px">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.number"
              :disabled="updateState || scope.row.dataSubmitState == 20"
              @change="qualified(scope.$index)"
            ></el-input>
          </template>
        </el-table-column>
        <!-- <el-table-column label="质量指标">
          <template slot-scope="scope">
            {{ scope.row.qualityIndex }}
          </template>
        </el-table-column> -->
        <el-table-column label="是否合格" width="70px">
          <template slot-scope="scope">{{ scope.row.resultStatus }}</template>
        </el-table-column>
        <!-- <el-table-column label="检测人" width="130px">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.detectionPerson"
              :disabled="
                updateState ||
                scope.row.dataSubmitState == 20 ||
                scope.row.dataOrigin == 1
              "
              @change="qualified(scope.$index)"
            ></el-input>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="数据源">
          <template slot-scope="scope">
            <span>{{ dataOrigin(scope.row.dataOrigin) }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="检测日期" width="170px">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.detectionDate"
              :disabled="
                updateState ||
                scope.row.dataSubmitState == 20 ||
                scope.row.dataOrigin == 1
              "
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="是否检测" width="170px">
          <template slot-scope="scope">
            <el-checkbox
              v-model="scope.row.detectionStateBool"
              :disabled="
                updateState ||
                scope.row.dataSubmitState == 20 ||
                scope.row.dataOrigin == 1
              "
              >不检测</el-checkbox
            >
          </template>
        </el-table-column>

        <el-table-column
          v-if="!updateState && systemType == 'thirdparty'"
          fixed="right"
          width="110px"
          label="操作"
        >
          <template slot-scope="scope">
            <div class="base-table-operation">
              <el-link
                style="flex-shrink: 0"
                :disabled="scope.row.dataSubmitState == 20"
                :type="
                  scope.row.experimentTemplateRecordId === null ||
                  scope.row.experimentTemplateRecordId.length === 0
                    ? 'primary'
                    : 'warning'
                "
                @click="selUnitELN(scope.$index)"
                >{{ linkText(scope.row.experimentTemplateRecordId) }}</el-link
              >
              <!-- <el-link type="primary" @click="cancelQuoteELN(scope.$index)"
                >取消引用</el-link
              >-->
              <el-link
                style="flex-shrink: 0; margin-left: 10px"
                :disabled="scope.row.dataSubmitState == 20"
                type="primary"
                @click="selectQuote(scope.row.experimentTemplateRecordId)"
              >
                查看
              </el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div
        v-if="!updateState"
        slot="footer"
        class="dialog-footer"
        align="center"
      >
        <el-button
          :disabled="!submitLoad"
          type="primary"
          style="width: 100px"
          @click="submit"
          >部分提交</el-button
        >
        <el-button
          :disabled="!submitLoad"
          type="primary"
          style="width: 100px"
          @click="onSubmit(12)"
          >全部提交</el-button
        >
        <el-button :disabled="!submitLoad" type="primary" @click="tsSubmit(11)"
          >暂 存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
      <!-- 批量录入检测结果 -->
      <el-dialog
        title="批量录入检测结果"
        :visible.sync="detectionResultVisible"
        width="20%"
        center
        append-to-body
      >
        <el-form
          ref="detectionResultForm"
          :model="detectionResultForm"
          :rules="detectionResultFormRules"
        >
          <el-form-item
            label="检测结果"
            prop="detectionResult"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="detectionResultForm.detectionResult"
              autocomplete="off"
              placeholder="请输入检测结果"
              style="width: 200px"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="detectionResultVisible = false">取 消</el-button>
          <el-button type="primary" @click="resultConfirm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 批量录入检测日期 -->
      <el-dialog
        title="批量录入检测日期"
        :visible.sync="detectionDateVisible"
        width="20%"
        center
        append-to-body
      >
        <el-form
          ref="detectionDateForm"
          :model="detectionDateForm"
          :rules="detectionDateFormRules"
        >
          <el-form-item
            label="检测日期"
            prop="detectionDate"
            :label-width="formLabelWidth"
          >
            <el-date-picker
              v-model="detectionDateForm.detectionDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择检测日期"
              style="width: 200px"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="detectionDateVisible = false">取 消</el-button>
          <el-button type="primary" @click="detectionDateConfirm"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-dialog>
    <ExperimentTemplateRecordDialog
      v-if="recordDialogFormVisible"
      ref="ExperimentTemplateRecordDialog"
      :record-dialog-form-visible.sync="recordDialogFormVisible"
      :experiment-template-record-id-list.sync="experimentTemplateRecordIdList"
      :experiment-pagination.sync="experimentPagination"
      :task-id.sync="data.id"
      :sample-info-id.sync="sampleInfoId"
      :detection-item-id.sync="detectionItemId"
      @recordClose="recordClose"
    />
    <!-- 打印页面 -->
    <ExperimentTemplateRecordEdit
      v-if="dialogFormVisibleEdit"
      ref="ExperimentTemplateRecordEdit"
      v-model="recordFormData"
      :page-view-mode="'print'"
      :readonly="true"
      :dialog-form-visible.sync="dialogFormVisibleEdit"
    />
  </div>
</template>

<script>
import _ from "lodash";
import {
  // entrustTaskResultEntryList,
  entrustTaskSampleInfoResult,
  EntrustTaskSampleInfoResultAdd,
  DetailList,
} from "../../api/EntrustTaskManage/EntrustTask";
// import { UpdateResultBitch } from "../../api/EntrustTaskManage/EntrustTaskSampleInfo";
import { formatTime } from "../../utils/time";
import { getUserList } from "../../api/Permission/PermissionUser";
import ExperimentTemplateRecordDialog from "../../components/ExperimentTemplateRecord/ExperimentTemplateRecordDialog.vue";
import { getConfigByKey, getDictList } from "../../api/System/SystemDict";
import { getSingleList } from "../../api/ELN/ExperimentTemplateRecord";
import ExperimentTemplateRecordEdit from "@/ModuleEln/ModuleEln/views/ModuleEln/ExperimentTemplateRecord/ExperimentTemplateRecordEdit.vue";
export default {
  name: "EntrustTaskDataResult",
  components: {
    ExperimentTemplateRecordDialog,
    ExperimentTemplateRecordEdit,
  },

  props: {
    updateState: {
      type: Boolean, // 布尔
      default: false, // 必填
    },
    dialogFormVisible: {
      type: Boolean, // 布尔
      default: false, // 必填
    },
    data: {
      type: Object, // 数组 // 对象或数组默认值必须从一个工厂函数获取
      default: () => {},
    },
  },
  data() {
    return {
      submitLoad: true,
      query: {
        sampleNum: "0",
        entrustNum: "0",
      },
      sampleNumList: [],
      entrustNumList: [],
      detectionStateBool: false,
      detectionDate: "",
      sampleInfoId: "",
      detectionItemId: "",
      decisionSymbolList: [],
      experimentPagination: {
        pageIndex: 1,
        pageSize: 10,
      },

      // 实验记录单id
      experimentTemplateRecordIdList: [],
      dialogFormVisibleEdit: false,
      // 批量录入的结果值
      result: "",
      selState: [],
      recordDialogFormVisible: false,
      poes: 0,
      spanArr: [],
      userData: [],
      tableDatas: [],
      // 表单验证
      userArrary: [],
      list: [],
      formRules: {
        detectionPersonId: [{ required: true, message: "检测人不能为空" }],
        planDetectionDate: [
          { required: true, message: "计划检测时间不能为空" },
        ],
      },
      detectionResultFormRules: {
        detectionResult: [{ required: true, message: "检测结果不能为空" }],
      },
      detectionDateFormRules: {
        detectionDate: [{ required: true, message: "检测日期不能为空" }],
      },
      innerDialogFormVisible: false,
      formLabelWidth: "100px",
      loading: false,
      formData: {
        id: "",
        entrustTaskStatus: 0,
        orderNum: "",
        department: "",
        entrustDateTime: "",
        planDetectionDate: "",
        methodStandard: "",
        methodStandardName: "",
        resultDetectionPerson: "",
        resultDetectionPersonId: "",
        dataStatus: "",
      },
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      choiceIndex: -1,
      systemType: "",

      recordFormData: [],
      detectionResultVisible: false,
      detectionDateVisible: false,
      detectionResultForm: {
        detectionResult: "",
      },
      detectionDateForm: {
        detectionDate: "",
      },
    };
  },
  computed: {
    entrustTaskSampleInfoResultDtos() {
      if (this.query.sampleNum !== "0" && this.query.entrustNum !== "0") {
        return this.formData.entrustTaskSampleInfoResultDtos.filter(
          (record) => {
            return (
              record.sampleNum.includes(this.query.sampleNum) &&
              record.entrustOrderNum.includes(this.query.entrustNum)
            );
          }
        );
      } else if (this.query.sampleNum !== "0") {
        return this.formData.entrustTaskSampleInfoResultDtos.filter(
          (record) => {
            return record.sampleNum.includes(this.query.sampleNum);
          }
        );
      } else if (this.query.entrustNum !== "0") {
        return this.formData.entrustTaskSampleInfoResultDtos.filter(
          (record) => {
            return record.entrustOrderNum.includes(this.query.entrustNum);
          }
        );
      } else {
        return this.formData.entrustTaskSampleInfoResultDtos;
      }
    },
  },
  watch: {
    formData(val) {
      this.doLayout();
    },
  },
  created() {
    // this.formData.entrustTaskNum = this.data.entrustTaskNum;
    // this.formData.entrustOrderNumList = this.data.entrustOrderNumList;
    // this.formData.detectionItemName = this.data.detectionItemName;
    // this.formData.sampleInfoName = this.data.sampleInfoName;
    // this.formData.sampleInfoNum = this.data.sampleInfoNum;
    // this.formData.planDetectionDate = this.data.planDetectionDate;
    // this.formData.remark = this.data.remark;
    // 判定符号
    getDictList({ dictCode: "DecisionSymbol" }).then((res) => {
      this.decisionSymbolList = res.data;
    });

    this.innerDialogFormVisible = this.dialogFormVisible;
    getUserList({}).then((res) => {
      this.userData = res.data;
    });

    // 查询字典表判断系统类型
    getConfigByKey("SystemType").then((res) => {
      this.systemType = res.data[0].value;
    });
    this.loading = true;
    this.getList();
  },
  methods: {
    sampleNumChange() {},
    entrustNumChange() {},
    // 部分提交判断是否全部勾选如果全部勾选调用全部提交按钮的方法
    submit() {
      if (
        this.tableDatas.length ===
        this.formData.entrustTaskSampleInfoResultDtos.length
      ) {
        this.onSubmit(12);
      } else {
        this.portiOnSubmit();
      }
    },
    // 清除数据
    clearQuoteData() {
      for (
        let i = 0;
        i < this.formData.entrustTaskSampleInfoResultDtos.length;
        i++
      ) {
        this.formData.entrustTaskSampleInfoResultDtos[i].dataOrigin = 0;
        this.formData.entrustTaskSampleInfoResultDtos[i].detectionPerson = "";
        this.formData.entrustTaskSampleInfoResultDtos[i].result = "";
        this.formData.entrustTaskSampleInfoResultDtos[i].detectionDate = null;
      }
    },
    // 指标
    indicator(decisionSymbol, number) {
      var indicator = "";
      if (decisionSymbol !== null && String(decisionSymbol) !== "") {
        indicator += decisionSymbol;
      }
      if (number !== null && String(number) !== "") {
        indicator += number;
      }
      return indicator;
    },
    dataOrigin(data) {
      if (data === 0 || data === null) {
        return "手动录入";
      } else {
        return "机器采集";
      }
    },
    linkText(data) {
      if (data === null || data.length === 0) {
        return "引用";
      }
      return `引用(${data.length})`;
    },
    // 引用数据
    quoteData() {
      // 查询根据样品编号数据采集
      var data = this.entrustTaskSampleInfoResultDtos.map((item) => ({
        SampleNum: item.sampleNum,
        DetectionItem: item.detectionItem,
      }));
      DetailList({ sampleDetections: data, pageSize: 9999 }).then((res) => {
        for (let i = 0; i < res.data.dataList.length; i++) {
          for (
            let o = 0;
            o < this.formData.entrustTaskSampleInfoResultDtos.length;
            o++
          ) {
            if (
              res.data.dataList[i].sampleNum ===
                this.formData.entrustTaskSampleInfoResultDtos[o].sampleNum &&
              (res.data.dataList[i].name ===
                this.formData.entrustTaskSampleInfoResultDtos[o]
                  .detectionItem ||
                res.data.dataList[i].name ===
                  this.formData.entrustTaskSampleInfoResultDtos[o].minuteItem)
            ) {
              this.formData.entrustTaskSampleInfoResultDtos[o].detectionPerson =
                res.data.dataList[i].detectionPerson;
              this.formData.entrustTaskSampleInfoResultDtos[o].dataOrigin = 1;
              this.formData.entrustTaskSampleInfoResultDtos[o].result =
                res.data.dataList[i].result;
              this.formData.entrustTaskSampleInfoResultDtos[o].detectionDate =
                res.data.dataList[i].detectionDateTime;
              this.qualified(o);
            }
          }
        }
      });
    },
    tableHeight() {
      this.$nextTick(() => {
        this.$refs["table"].doLayout();
      });
    },
    /* 重新渲染table组件 */
    doLayout() {
      const that = this;
      this.$nextTick(() => {
        that.$refs.table.doLayout();
      });
    },
    setDisabled(row) {
      if (Number(row.dataSubmitState) === 20) {
        return false;
      } else {
        return true;
      }
    },
    // 暂存
    tsSubmit: _.throttle(function() {
      if (this.submitLoad) {
        this.submitLoad = false;
        for (
          var i = 0;
          i < this.formData.entrustTaskSampleInfoResultDtos.length;
          i++
        ) {
          if (
            this.formData.entrustTaskSampleInfoResultDtos[i].dataSubmitState ===
            0
          ) {
            this.formData.entrustTaskSampleInfoResultDtos[
              i
            ].dataSubmitState = 10;
          }
        }
        this.UpdateResultBitchFun(11);
      }
    }, 2000),
    // 部分提交
    portiOnSubmit: _.throttle(function() {
      if (this.submitLoad) {
        this.submitLoad = false;
        var xuhao = "";
        if (this.tableDatas === null || this.tableDatas.length === 0) {
          this.$message.warning("请选择数据");
          this.submitLoad = true;
          return;
        }
        for (let i = 0; i < this.tableDatas.length; i++) {
          if (
            (this.tableDatas[i].result === "" ||
              this.tableDatas[i].result === null) &&
            !this.tableDatas[i].detectionStateBool
          ) {
            this.$message.warning("录入结果不能为空!");
            this.submitLoad = true;
            return false;
          }

          if (this.tableDatas[i].resultStatus === "不合格") {
            if (xuhao.indexOf(this.tableDatas[i].serialNo) === -1) {
              if (xuhao === "") {
                xuhao += this.tableDatas[i].serialNo;
              } else {
                xuhao += "、" + this.tableDatas[i].serialNo;
              }
            }
          }
          this.tableDatas[i].dataSubmitState = 20;
        }

        var data = JSON.parse(JSON.stringify(this.formData));
        data.entrustTaskSampleInfoResultDtos = this.tableDatas;
        data.entrustTaskStatus = 11;

        if (xuhao !== "") {
          var msg = "序号" + xuhao + "检测项目结果不合格，请确认是否继续提交?";
          this.$confirm(msg, "提示", {
            confirmButtonText: "继续提交",
            cancelButtonText: "取消",
            type: "warning",
            center: true,
          })
            .then(() => {
              this.UpdateResultBitchFun(11, data);
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "操作取消",
              });
              this.submitLoad = true;
            });
        } else {
          this.UpdateResultBitchFun(11, data);
        }
      }
    }, 2000),
    // 查看
    selectQuote(ids) {
      if (!ids || !ids.length) {
        this.$message.warning("请先引用数据再进行查看");
        return;
      }
      const promiseList = ids.map((id) => {
        return getSingleList({ Id: id });
      });
      Promise.all(promiseList).then((res) => {
        this.recordFormData = res.map((x) => x.data);
        this.dialogFormVisibleEdit = true;
      });
    },
    changePrintPage() {},
    // 是否合格
    qualified(index) {
      this.formData.entrustTaskSampleInfoResultDtos[index].qualityIndex = "";
      var row = this.formData.entrustTaskSampleInfoResultDtos[index];
      if (row.decisionSymbol != null) {
        this.formData.entrustTaskSampleInfoResultDtos[index].qualityIndex =
          row.decisionSymbol;
      } else {
        this.formData.entrustTaskSampleInfoResultDtos[index].resultStatus =
          "合格";
        return false;
      }
      if (row.number != null) {
        this.formData.entrustTaskSampleInfoResultDtos[index].qualityIndex =
          this.formData.entrustTaskSampleInfoResultDtos[index].qualityIndex +
          row.number;
      } else {
        this.formData.entrustTaskSampleInfoResultDtos[index].resultStatus =
          "合格";
        return false;
      }
      var symbol = row.decisionSymbol;
      var num = row.number;
      var numReg = /^(\-|\+)?\d+(\.\d+)?$/;
      var numRe = new RegExp(numReg);
      this.formData.entrustTaskSampleInfoResultDtos[index].rresultStatus = "";
      var state = null;
      if (!numRe.test(Number(num)) || !numRe.test(Number(row.result))) {
        if (num === row.result) {
          state = true;
        } else if (symbol === "∈") {
          state = false;
          if (row.result !== null && row.result !== "") {
            if (numRe.test(Number(row.result))) {
              var arr = num.split("-");
              if (numRe.test(Number(arr[0])) && numRe.test(Number(arr[1]))) {
                if (Number(arr[0]) > Number(arr[1])) {
                  state =
                    Number(arr[0]) >= Number(row.result) &&
                    Number(row.result) >= Number(arr[1]);
                } else if (Number(arr[0]) < Number(arr[1])) {
                  state =
                    Number(arr[0]) <= Number(row.result) &&
                    Number(row.result) <= Number(arr[1]);
                }
              }
            }
          }
        } else {
          state = false;
          // 截取检测结果第一个字符
          var resultSymbol = String(row.result).substring(0, 1);
          // 结果
          var result = String(row.result).substring(
            1,
            String(row.result).length
          );
          if (numRe.test(result)) {
            if (resultSymbol === ">" || resultSymbol === "≥") {
              state = false;
              if (
                (symbol === "≥" && Number(result) >= Number(num)) ||
                (symbol === ">" && Number(result) > Number(num))
              ) {
                state = true;
              }
            } else if (resultSymbol === "<" || resultSymbol === "≤") {
              state = false;
              if (
                (symbol === "≤" && Number(result) <= Number(num)) ||
                (symbol === "<" && Number(result) < Number(num))
              ) {
                state = true;
              }
            } else {
              state = false;
            }
          } else {
            state = false;
            // 判断是否为 未检出和无
            if (row.result === "未检出" || row.result === "无") {
              state = true;
            } else {
              state = false;
            }
          }
        }
      } else {
        state = this.resultJudgment(symbol, numRe, num, row.result);
      }

      if (
        this.formData.entrustTaskSampleInfoResultDtos[index].number !== null &&
        this.formData.entrustTaskSampleInfoResultDtos[index].number !== ""
      ) {
        if (state) {
          this.formData.entrustTaskSampleInfoResultDtos[index].resultStatus =
            "合格";
        } else if (!state && state != null) {
          this.formData.entrustTaskSampleInfoResultDtos[index].resultStatus =
            "不合格";
        } else {
          this.formData.entrustTaskSampleInfoResultDtos[index].resultStatus =
            "";
        }
      } else {
        this.formData.entrustTaskSampleInfoResultDtos[index].resultStatus = "";
      }
    },

    // 结果判断
    // symbol判定符号
    // numRe正则
    // num判定数值
    // result结果
    resultJudgment(symbol, numRe, num, result) {
      var state = null;
      if (symbol === "≥") {
        if (result !== null && result !== "") {
          if (numRe.test(Number(num)) && numRe.test(Number(result))) {
            state = Number(result) >= Number(num);
          }
        }
      } else if (symbol === "≤") {
        if (result !== null && result !== "") {
          if (numRe.test(Number(num)) && numRe.test(Number(result))) {
            state = Number(result) <= Number(num);
          }
        }
      } else if (symbol === "∈") {
        if (result !== null && result !== "") {
          if (numRe.test(Number(result))) {
            var arr = num.split("-");
            if (numRe.test(Number(arr[0])) && numRe.test(Number(arr[1]))) {
              if (Number(arr[0]) > Number(arr[1])) {
                state =
                  Number(arr[0]) >= Number(result) &&
                  Number(result) >= Number(arr[1]);
              } else if (Number(arr[0]) < Number(arr[1])) {
                state =
                  Number(arr[0]) <= Number(result) &&
                  Number(result) <= Number(arr[1]);
              }
            }
          }
        }
      } else if (symbol === ">") {
        if (result !== null && result !== "") {
          if (numRe.test(Number(num)) && numRe.test(Number(result))) {
            state = Number(result) > Number(num);
          }
        }
      } else if (symbol === "<") {
        if (result !== null && result !== "") {
          if (numRe.test(Number(num)) && numRe.test(Number(result))) {
            state = Number(result) < Number(num);
          }
        }
      } else {
        if (num === result) {
          state = true;
        } else {
          state = false;
        }
      }
      return state;
    },
    // 批量确定结果
    batchSetResult() {
      if (this.tableDatas.length === 0 || this.tableDatas === null) {
        this.$message.warning("请选择数据!");
        return false;
      }
      this.detectionResultVisible = true;
    },
    resultConfirm() {
      this.$refs["detectionResultForm"].validate((valid) => {
        if (valid) {
          for (let o = 0; o < this.tableDatas.length; o++) {
            for (
              let i = 0;
              i < this.formData.entrustTaskSampleInfoResultDtos.length;
              i++
            ) {
              if (
                this.tableDatas[o].id ===
                this.formData.entrustTaskSampleInfoResultDtos[i].id
              ) {
                this.formData.entrustTaskSampleInfoResultDtos[i].result =
                  this.detectionResultForm.detectionResult;
                this.qualified(i);
              }
            }
          }
          this.detectionResultVisible = false;
        }
      });
    },

    // 批量录入检测日期
    batchSetDate() {
      if (this.tableDatas.length === 0 || this.tableDatas === null) {
        this.$message.warning("请选择数据!");
        return false;
      }
      this.detectionDateVisible = true;
    },
    detectionDateConfirm() {
      this.$refs["detectionDateForm"].validate((valid) => {
        if (valid) {
          for (let o = 0; o < this.tableDatas.length; o++) {
            for (
              let i = 0;
              i < this.formData.entrustTaskSampleInfoResultDtos.length;
              i++
            ) {
              if (
                this.tableDatas[o].id ===
                this.formData.entrustTaskSampleInfoResultDtos[i].id
              ) {
                this.formData.entrustTaskSampleInfoResultDtos[i].detectionDate =
                  this.detectionDateForm.detectionDate;
              }
            }
          }
          this.detectionDateVisible = false;
        }
      });
    },
    // 批量设置检测状态
    detectionStateBoolConfirm() {
      if (this.tableDatas.length === 0 || this.tableDatas === null) {
        this.$message.warning("请选择数据!");
        return false;
      }

      for (let o = 0; o < this.tableDatas.length; o++) {
        for (
          let i = 0;
          i < this.formData.entrustTaskSampleInfoResultDtos.length;
          i++
        ) {
          if (
            this.tableDatas[o].id ===
            this.formData.entrustTaskSampleInfoResultDtos[i].id
          ) {
            this.formData.entrustTaskSampleInfoResultDtos[
              i
            ].detectionStateBool = this.detectionStateBool;
          }
        }
      }
    },

    // 批量录入结果确定
    confirm() {
      if (this.tableDatas.length === 0 || this.tableDatas === null) {
        this.$message.warning("请选择数据!");
        return false;
      }

      for (let o = 0; o < this.tableDatas.length; o++) {
        for (
          let i = 0;
          i < this.formData.entrustTaskSampleInfoResultDtos.length;
          i++
        ) {
          if (
            this.tableDatas[o].id ===
            this.formData.entrustTaskSampleInfoResultDtos[i].id
          ) {
            if (this.detectionResultForm.detectionResult) {
              this.formData.entrustTaskSampleInfoResultDtos[i].result =
                this.detectionResultForm.detectionResult;
              this.qualified(i);
            }
            if (this.detectionDateForm.detectionDate) {
              this.formData.entrustTaskSampleInfoResultDtos[i].detectionDate =
                this.detectionDateForm.detectionDate;
            }

            this.formData.entrustTaskSampleInfoResultDtos[
              i
            ].detectionStateBool = this.detectionStateBool;
          }
        }
      }
    },
    // 关闭选择eln实验记录单
    // state等于1是确定等于0是取消
    recordClose(data, experimentPagination, state) {
      this.experimentPagination = {};
      this.experimentPagination = experimentPagination;
      if (state === 1) {
        if (data != null && data.length !== 0) {
          this.selState[this.choiceIndex] = false;
          if (data !== null && data.length !== 0) {
            this.formData.entrustTaskSampleInfoResultDtos[
              this.choiceIndex
            ].experimentTemplateRecordId = [];
            this.formData.entrustTaskSampleInfoResultDtos[
              this.choiceIndex
            ].experimentTemplateRecordMongoId = [];
            this.formData.entrustTaskSampleInfoResultDtos[
              this.choiceIndex
            ].detectionDate = data[0].detectionTime;
            for (let i = 0; i < data.length; i++) {
              this.formData.entrustTaskSampleInfoResultDtos[
                this.choiceIndex
              ].experimentTemplateRecordId.push(data[i].id);
              this.formData.entrustTaskSampleInfoResultDtos[
                this.choiceIndex
              ].experimentTemplateRecordMongoId.push(data[i]._id);
            }
            if (
              this.formData.entrustTaskSampleInfoResultDtos[this.choiceIndex]
                .result === null ||
              this.formData.entrustTaskSampleInfoResultDtos[this.choiceIndex]
                .result === ""
            ) {
              if (
                data[0].tagResultValues.length !== 0 &&
                data[0].tagResultValues != null
              ) {
                var flag = false;
                data[0].tagResultValues.map((x) => {
                  if (
                    x.sysBusinessDetectionItemId ===
                    this.formData.entrustTaskSampleInfoResultDtos[
                      this.choiceIndex
                    ].detectionItemId
                  ) {
                    this.formData.entrustTaskSampleInfoResultDtos[
                      this.choiceIndex
                    ].result = x.v;
                    flag = true;
                  }
                });

                if (!flag) {
                  if (
                    data[0].tagValues.length !== 0 &&
                    data[0].tagValues != null
                  ) {
                    this.formData.entrustTaskSampleInfoResultDtos[
                      this.choiceIndex
                    ].result = data[0].tagValues[0].v;
                    this.qualified(this.choiceIndex);
                  }
                }
                this.qualified(this.choiceIndex);
              } else if (
                data[0].tagValues.length !== 0 &&
                data[0].tagValues != null
              ) {
                this.formData.entrustTaskSampleInfoResultDtos[
                  this.choiceIndex
                ].result = data[0].tagValues[0].v;
                this.qualified(this.choiceIndex);
              }
            }

            // }
            // }
          }
          this.choiceIndex = -1;
        } else {
          this.formData.entrustTaskSampleInfoResultDtos[
            this.choiceIndex
          ].experimentTemplateRecordId = [];

          this.experimentPagination.pageIndex = 1;
          this.experimentPagination.pageSize = 10;
        }
      }
    },
    // 引用eln
    selUnitELN(index) {
      this.choiceIndex = index;
      this.experimentTemplateRecordIdList = [];
      var experimentTemplateRecordId =
        this.formData.entrustTaskSampleInfoResultDtos[this.choiceIndex]
          .experimentTemplateRecordId;

      if (
        experimentTemplateRecordId !== null &&
        experimentTemplateRecordId.length !== 0
      ) {
        this.experimentTemplateRecordIdList = experimentTemplateRecordId;
      }
      this.sampleInfoId =
        this.formData.entrustTaskSampleInfoResultDtos[
          this.choiceIndex
        ].sysBusinessSampleInfoId;

      this.detectionItemId =
        this.formData.entrustTaskSampleInfoResultDtos[
          this.choiceIndex
        ].detectionItemId;
      this.recordDialogFormVisible = true;
      // 获取检测项目和样品关联关系表ID
    },
    cancelQuoteELN(index) {
      this.formData.entrustTaskSampleInfoResultDtos[
        index
      ].experimentTemplateRecordId = [];
      this.formData.entrustTaskSampleInfoResultDtos[
        index
      ].experimentTemplateRecordMongoId = [];
    },
    formatTime,
    // 对于需要合并的行做标记
    getSpanArr(data) {
      var rowIndex = 1;
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          this.poes = this.spanArr.length - 1;
          data[i].serialNo = rowIndex;
          rowIndex++;
        } else {
          if (Number(data[i].parentItemId) !== 0) {
            // 判断当前元素与上一个元素是否相同
            if (
              data[i].parentItemId === data[i - 1].parentItemId &&
              data[i].sampleNum === data[i - 1].sampleNum
            ) {
              this.spanArr[this.poes] += 1;
              this.spanArr.push(0);
              data[i].serialNo = rowIndex - 1;
            } else {
              this.spanArr.push(1);
              this.poes = this.spanArr.length - 1;
              data[i].serialNo = rowIndex;
              rowIndex++;
            }
          } else {
            this.spanArr.push(1);
            this.poes = this.spanArr.length - 1;
            data[i].serialNo = rowIndex;
            rowIndex++;
          }
        }
      }
    },
    // 合并行或列
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (
        columnIndex === 2 ||
        columnIndex === 1 ||
        columnIndex === 3 ||
        columnIndex === 4
      ) {
        const _row = this.spanArr[rowIndex];
        return {
          rowspan: _row,
          colspan: 1,
        };
      }
    },
    currentChange(val) {
      this.pagination.pageIndex = val;
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
    },
    cancel() {
      this.innerDialogFormVisible = false;
    },
    closeDialog() {
      // 动画结束后在清空表单 防止页面闪烁
      this.$refs.formData.resetFields();
      this.innerDialogFormVisible = false;
      this.$emit("update:updateState", false);
      this.$emit("update:dialogFormVisible", false);
      this.$emit("close");
    },
    onSubmit: _.throttle(function(state) {
      if (this.submitLoad) {
        this.submitLoad = false;
        // if (this.tableDatas.length <= 0) {
        //   this.$message.warning("请选择最少一条数据");
        //   return;
        // }
        // if (this.list.length !== this.tableDatas.length) {
        //   this.$message.warning("检测结果录入必须全部填写!");
        //   return;
        // }
        var data = JSON.parse(JSON.stringify(this.formData));
        data.entrustTaskSampleInfoResultDtos = [];
        if (state === 12) {
          var xuhao = "";
          for (
            var i = 0;
            i < this.formData.entrustTaskSampleInfoResultDtos.length;
            i++
          ) {
            // if (
            //   this.formData.entrustTaskSampleInfoResultDtos[i].dataSubmitState !=
            //   20
            // ) {

            if (
              (this.formData.entrustTaskSampleInfoResultDtos[i].result === "" ||
                this.formData.entrustTaskSampleInfoResultDtos[i].result ===
                  null) &&
              !this.formData.entrustTaskSampleInfoResultDtos[i]
                .detectionStateBool
            ) {
              this.submitLoad = true;
              this.$message.warning("录入结果不能为空!");
              return;
            }
            if (
              this.formData.entrustTaskSampleInfoResultDtos[i].resultStatus ===
              "不合格"
            ) {
              if (
                xuhao.indexOf(
                  this.formData.entrustTaskSampleInfoResultDtos[i].serialNo
                ) === -1
              ) {
                if (xuhao === "") {
                  xuhao +=
                    this.formData.entrustTaskSampleInfoResultDtos[i].serialNo;
                } else {
                  xuhao +=
                    "、" +
                    this.formData.entrustTaskSampleInfoResultDtos[i].serialNo;
                }
              }
            }
            // }
          }

          if (xuhao !== "") {
            var msg =
              "序号" + xuhao + "检测项目结果不合格，请确认是否继续提交?";
            this.$confirm(msg, "提示", {
              confirmButtonText: "继续提交",
              cancelButtonText: "取消",
              type: "warning",
              center: true,
            })
              .then(() => {
                this.allSubmit(state, data);
              })
              .catch(() => {
                this.submitLoad = true;

                this.$message({
                  type: "info",
                  message: "操作取消",
                });
              });
          } else {
            this.allSubmit(state, data);
          }
        } else {
          this.allSubmit(state, data);
        }
      }
    }, 2000),

    allSubmit(state, data) {
      for (
        var i = 0;
        i < this.formData.entrustTaskSampleInfoResultDtos.length;
        i++
      ) {
        this.formData.entrustTaskSampleInfoResultDtos[i].dataSubmitState = 20;
        data.entrustTaskSampleInfoResultDtos.push(
          this.formData.entrustTaskSampleInfoResultDtos[i]
        );
      }
      this.UpdateResultBitchFun(state, data);
    },

    UpdateResultBitchFun(status, data) {
      if (data != null) {
        data.dataStatus = data.entrustTaskStatus;
        data.entrustTaskStatus = status;

        EntrustTaskSampleInfoResultAdd(data).then((res) => {
          this.submitLoad = true;

          this.closeDialog();
        });
      } else {
        this.formData.dataStatus = this.formData.entrustTaskStatus;
        this.formData.entrustTaskStatus = status;

        EntrustTaskSampleInfoResultAdd(this.formData).then((res) => {
          this.submitLoad = true;

          this.closeDialog();
        });
      }
    },
    getList() {
      this.list = [];
      var obj = {};
      obj.entrustTaskIdList = this.data.id;
      entrustTaskSampleInfoResult(obj)
        .then((res) => {
          this.formData = res.data;
          if (
            res.data.resultDetectionPersonId !== null &&
            res.data.resultDetectionPersonId !== "" &&
            res.data.resultDetectionPersonId !== 0 &&
            res.data.resultDetectionPersonId !== "0"
          ) {
            this.formData.resultDetectionPerson =
              res.data.resultDetectionPerson;
            this.formData.resultDetectionPersonId =
              res.data.resultDetectionPersonId;
          } else {
            this.formData.resultDetectionPerson = this.$store.getters.name;
            this.formData.resultDetectionPersonId =
              this.$store.getters.currentUserId;
          }

          for (
            let i = 0;
            i < this.formData.entrustTaskSampleInfoResultDtos.length;
            i++
          ) {
            this.selState[i] = true;
            this.qualified(i);
          }
          this.getSpanArr(this.formData.entrustTaskSampleInfoResultDtos);
          this.sampleNumList = [];
          this.entrustNumList = [];
          this.sampleNumList.push({ id: "0", name: "全部" });
          this.entrustNumList.push({ id: "0", name: "全部" });
          this.formData.entrustTaskSampleInfoResultDtos.map((item) => {
            var obj = {};
            obj.id = item.entrustOrderNum;
            obj.name = item.entrustOrderNum;
            this.entrustNumList.push(obj);
            var obj2 = {};
            obj2.id = item.sampleNum;
            obj2.name = item.sampleNum;
            this.sampleNumList.push(obj2);
          });

          this.sampleNumList = [
            ...new Set(this.sampleNumList.map(JSON.stringify)),
          ].map(JSON.parse);
          this.entrustNumList = [
            ...new Set(this.entrustNumList.map(JSON.stringify)),
          ].map(JSON.parse);
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 选择列表
    handleSelectionChange(val) {
      this.tableDatas = val;
    },
  },
};
</script>
<style lang="scss">
.el-form-item {
  .el-form-item__content {
    text-align: left;
  }
}
</style>
